package gofunc

import (
	"bytes"
	"encoding/base64"
	"github.com/skip2/go-qrcode"
	"image"
	"image/jpeg"
	"image/png"
	"io/ioutil"
	"os"
)

type ImgFunc struct {
}

// 将一个url转换为png图片再转换为base64
func (self *ImgFunc) UrlToImgBase64(url string) (_base64 string) {
	pic, _ := qrcode.Encode(url, qrcode.Medium, 256)
	r := bytes.NewReader(pic)
	img, _ := png.Decode(r)
	emptyBuff := bytes.NewBuffer(nil) //开辟一个新的空buff
	png.Encode(emptyBuff, img)
	base64len := emptyBuff.Len() / 3
	if emptyBuff.Len()%3 != 0 {
		base64len++
	}
	base64len = base64len * 4
	//dist的长度为 二进制的长度向上到3整除/3*4 base64的规则
	dist := make([]byte, base64len)
	base64.StdEncoding.Encode(dist, emptyBuff.Bytes()) //buff转成base64
	_base64 = "data:image/png;base64," + string(dist)
	return
}

func (self *ImgFunc) Img2JpgBase64(img image.Image) string {
	emptyBuff := bytes.NewBuffer(nil) //开辟一个新的空buff
	jpeg.Encode(emptyBuff, img, nil)  //img写入到buff
	//dist := make([]byte, 50000)                        //开辟存储空间
	//base64.StdEncoding.Encode(dist, emptyBuff.Bytes()) //buff转成base64
	//fmt.Println(string(dist))                          //输出图片base64(type = []byte)
	//_ = ioutil.WriteFile("./base64pic.txt", dist, 0666) //buffer输出到jpg文件中（不做处理，直接写到文件）
	imageBase64 := base64.StdEncoding.EncodeToString(emptyBuff.Bytes())
	return imageBase64

}

// 将图片保存到指定路径
func (self *ImgFunc) SaveJpeg2Dist(img image.Image, fileurl string) error {
	var imageBuf bytes.Buffer
	err := jpeg.Encode(&imageBuf, img, nil)
	if err != nil {
		return err
	}
	err2 := ioutil.WriteFile(fileurl, imageBuf.Bytes(), 06666)
	if err2 != nil {
		return err2
	}
	return nil
}

// 本地图片读取为image.Image
//
//	img, err2 := ReadImage("000000014439.jpg")
func (self *ImgFunc) ReadImage(path string) (image.Image, error) {
	file, err := os.Open(path)
	if err != nil {
		panic(err)
		return nil, err
	}
	defer file.Close()
	img, _, err := image.Decode(file)
	if err != nil {
		panic(err)
		return nil, err
	}
	return img, err
}

// 将图片转换为uint8的数组
func (self *ImgFunc) Img2Uint8(img image.Image) []uint8 {
	bounds := img.Bounds()
	w, h := bounds.Max.X, bounds.Max.Y
	var data []uint8
	for y := 0; y < h; y++ {
		for x := 0; x < w; x++ {
			r, g, b, _ := img.At(x, y).RGBA()
			data = append(data, uint8(r>>8))
			data = append(data, uint8(g>>8))
			data = append(data, uint8(b>>8))
		}
	}
	return data
}

// 将图片转换为uint8的数组
func (self *ImgFunc) Img2Uint8Bgr(img image.Image) []uint8 {
	bounds := img.Bounds()
	w, h := bounds.Max.X, bounds.Max.Y
	var data []uint8
	for y := 0; y < h; y++ {
		for x := 0; x < w; x++ {
			r, g, b, _ := img.At(x, y).RGBA()
			data = append(data, uint8(b>>8))
			data = append(data, uint8(g>>8))
			data = append(data, uint8(r>>8))

		}
	}
	return data
}
